package com.liruo.learn.spring.mvc.config.mvc;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * @Author:liruo
 * @Date:2023-02-12-23:56:35
 * @Desc
 */
//@Configuration
@Slf4j
public class MvcConfig implements WebMvcConfigurer {
    class LogHandlerInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            log.info("uri = {}", request.getRequestURI());
            return true;
        }
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LogHandlerInterceptor());
    }

    @Bean("/welcome*")
    public Controller welcomeNameController(){
        return (req,resp)->{
            ModelAndView mav = new ModelAndView();
            mav.addObject("now", LocalDateTime.now().toString());
            String name = req.getParameter("name");
            mav.addObject("name", name == null ? "你是?" : name);
            return mav;
        };
    }
}
